package com.qpcy.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.qpcy.dto.ProductListDto;
import com.qpcy.entity.Product;
import com.qpcy.service.ProductService;
import com.qpcy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import static com.qpcy.entity.table.ProductTableDef.PRODUCT;

/**
 * 产品 控制层。
 *
 * @author LENOVO
 * @since 2024-10-19
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 获取产品列表
     *
     * @param dto
     * @return
     */
    @PostMapping("/list")
    public ResponseResult list(@RequestBody ProductListDto dto) {
        // 创建分页对象
        Page<Product> productPage = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 构建查询条件
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select()
                .from(PRODUCT)
                //将null值排序到最后
                .orderBy("CASE WHEN product_sort IS NULL THEN 1 ELSE 0 END")
                .orderBy(PRODUCT.PRODUCT_SORT.asc());
        if (dto.getTypeId() != null) {
            queryWrapper.where(PRODUCT.TYPE_ID.eq(dto.getTypeId()));
        }
        if (dto.getKeyword() != null) {
            queryWrapper.and(q -> {
                q.where(PRODUCT.PRODUCT_NAME.like(dto.getKeyword()))
                        .or(PRODUCT.PRODUCT_NO.like(dto.getKeyword()));
            });
        }
        System.out.println(queryWrapper.toSQL());
        // 执行分页查询
        Page<Product> page = productService.page(productPage, queryWrapper);

        // 返回查询结果
        return ResponseResult.success(page);
    }

    /**
     * 获取产品详情
     *
     * @param productId
     * @return
     */
    @GetMapping("/detail")
    public ResponseResult getDetail(int productId) {
        return ResponseResult.success(productService.getById(productId));
    }

    /**
     * 新增产品
     *
     * @param product
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody Product product) {
        return ResponseResult.success(productService.save(product));
    }

    /**
     * 修改产品信息
     *
     * @param product
     * @return
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Product product) {
        return ResponseResult.success(productService.updateById(product));
    }

    /**
     * 删除产品
     *
     * @param productId
     * @return
     */
    @PostMapping("/delete")
    public ResponseResult delete(int productId) {
        return productService.deleteById(productId);
    }


}
